package com.atguigu.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;

@Configuration
public class RabbitmqConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;
    //生产者确认回调配置
    @PostConstruct //标注的方法会在构造器执行后立即调用一次
    public void init(){
        /*
        ack:true代表消息到达交换机
               false代表消息没有到达交换机
         */
        rabbitTemplate.setConfirmCallback((correlationData,ack,cause)->{
            System.out.println("ConfirmCallback ack: " + ack );
            System.out.println("ConfirmCallback cause: " + cause);
        });
        /*
            消息没有到达队列时回调：

         */
        rabbitTemplate.setReturnCallback((message,replyCode,replyText, exchange,routingKey)->{
            System.out.println("ReturnCallback replyCode: "+ replyCode);
            System.out.println("ReturnCallback replyText: "+ replyText);
            System.out.println("ReturnCallback exchange: "+ exchange);
            System.out.println("ReturnCallback routingKey: "+ routingKey);
            /*
            消息没有到达队列 重新投递消息，再次失败的消息可以存到日志中  或者redis缓存
             */
        });
    }

    //1、创建交换机
    @Bean
    public Exchange test1Exchange(){
        return ExchangeBuilder
                .topicExchange("test1.exchange") //交换机名
                .durable(false) //是否持久化
                .ignoreDeclarationExceptions() //是否忽略重复定义声明该交换机的异常
                .build();
    }
    //2、创建队列
    @Bean
    public Queue test1Queue(){
        return QueueBuilder
                .nonDurable("test1.queue") //不持久化 并指定队列名称
                .build();
    }
    //3、绑定交换机和队列
    @Bean
    public Binding test1Binding(Queue test1Queue,Exchange test1Exchange){
        return BindingBuilder.bind(test1Queue)
                    .to(test1Exchange)
                    .with("a.*")//路由key
                    .noargs();
    }
}
